import axios from './factory.js'
import url from './url.js';


class apiConfig {
    constructor() {
        this.api = {};
        this.api = {
            ...url
        }
    }
    //header:`{'X-CSRF-TOKEN':${params.token}` } 
    gets() {
        var all = {};
        for (var i in this.api) {
            all[i] = (url, params) => {
                var params = {
                    params: params,
                    time: new Date().getTime()
                }
                return axios.get(url, params);
            }
        }
        return all;
    }

    posts() {
        var all = {};
        for (var i in this.api) {
            all[i] = (url, params) => {
                /*params.time = new Date().getTime() ;
                params.header = {'X-CSRF-TOKEN':`${params.token}`} ;*/
                return axios.post(url, params);
            }
        }
        return all;
    }

    uploadPost() {
        var all = {};
        for (var i in this.api) {
            all[i] = (url, params) => {
                let param = new FormData();
                for (var i in params) {
                    param.append(i.toString(), params[i])
                }
                let config = {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    },
                    transformRequest: [function (data) {
                        return data;
                    }],
                }
                return axios.post(url, param, config);

            }
        }
        return all;
    }

}

export const gets = new apiConfig().gets();
export const posts = new apiConfig().posts();
export const uploadPost = new apiConfig().uploadPost();

export function formatTime(date, fmt) {
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substring(4 - RegExp.$1.length))
    }
    let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
    }
    for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
            let str = o[k] + ''
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str))
        }
    }
    return fmt
}

function padLeftZero(str) {
    return ('00' + str).substring(str.length)
}